<template>
	<view class="page">
		<scroll-view :style="{height:(systemInfo.windowHeight-imPlaceholderheight)+'px'}" scroll-y :scroll-into-view="scrollIntoView" class="msg-list">
				<!-- 聊天item -->
				<chat-item v-for="(item,index) in messages" :key='index' :item="item"></chat-item>
				<view class="list-last-item" id="list-last-item" key="list-last-item">
					<!-- 高度为0的 最后一个元素用于方便滚动到最后一个元素 -->
				</view>
		</scroll-view>
		<!-- 底部聊天输入框 -->
		<!-- #ifdef APP-PLUS -->
		<view class="bottom">
			<chat-input-bar @focus="showLast()" @send="doSend" :style="{paddingBottom:(keyboardHeight>0?systemInfo.safeAreaInsets.bottom/2:systemInfo.safeAreaInsets.bottom)+'px'}"/>
		</view>
		<!-- #endif -->
		<!-- #ifdef MP -->
		<view class="bottom" :style="{bottom:(keyboardHeight>0?keyboardHeight-systemInfo.safeAreaInsets.bottom:0)+'px',paddingBottom:systemInfo.safeAreaInsets.bottom+'px'}">
			<chat-input-bar @focus="showLast()"  @send="doSend" />
		</view>
		<!-- #endif -->
		
		<!-- #ifdef H5 -->
		<view class="bottom">
			<chat-input-bar @focus="showLast()"  @send="doSend" />
		</view>
		<!-- #endif -->
	</view>
</template>

<script>
	const cAi = uniCloud.importObject('c-ai',{customUI:true})
	export default {
		data() {
			return {
				//系统信息
				systemInfo: {
					safeAreaInsets: {
						bottom: 0
					}
				},
				scrollIntoView:'',
				messages:[{"time":"","icon":"https://mp-eeab6da6-80cd-4e80-844a-66b2a7203834.cdn.bspapp.com/cloudstorage/5fcdbeb8-01b2-47ac-b09f-1d1dcb1c6c60.png?x-oss-process=image/resize,m_fixed,w_160","name":"AI","content":"你好！有什么我可以帮助你的吗？","isMe":false,"role":"assistant","status":1,"chatId":1681804927670}],
				AIinfo:{
					time: '',
					icon: 'https://mp-eeab6da6-80cd-4e80-844a-66b2a7203834.cdn.bspapp.com/cloudstorage/5fcdbeb8-01b2-47ac-b09f-1d1dcb1c6c60.png?x-oss-process=image/resize,m_fixed,w_160',
					name: 'AI',
					content: '',
					isMe: false,
					role:'assistant',
					status:0 //0 加载中 1加载完成 -1出错 2持续输出
				},
				myInfo:{
					time: '',
					icon: 'https://mp-eeab6da6-80cd-4e80-844a-66b2a7203834.cdn.bspapp.com/cloudstorage/cd62d1b0-0f65-408a-ac09-204e7576b82a.png?x-oss-process=image/resize,m_fixed,w_160',
					name: '我',
					content: '',
					isMe: true,
					role:'user',
					status:1 //0 加载中 1加载完成 -1出错 2持续输出
				},
				//键盘高度
				keyboardHeight:0,
				sendData:[]
			}
		},
		computed:{
			imPlaceholderheight() {
				let imPlaceholderheight=this.keyboardHeight+this.systemInfo.safeAreaInsets.bottom
				return imPlaceholderheight
			},
		},
		methods: {
			async concatMsg(data){
				let lastData =this.messages[this.messages.length-1]
				let sendData = [data,{role:this.myInfo.role,content:'继续'}]
				try{
					const res = await cAi.chat(sendData)
					const choice = res.choices[0]
					lastData.content += res.reply
					// this.$nextTick(this.showLast)
					if(choice.finishReason=='stop'){
						lastData.status=1
					}else{
						lastData.status=2
						this.concatMsg(choice.message)
					}
				}catch(e){
					//TODO handle the exception
					lastData.status=-1
					lastData.content = '出错了，请稍后询问...'
					this.showLast()
					this.sendData=[]
				}
			},
			async doSend(val){
				let lastData =this.messages[this.messages.length-1]
				if(lastData.status==0||lastData.status==2){
					uni.showToast({
						title:'AI回答中，请稍后...',
						icon:'none'
					})
					return
				}
				
				let dataMy = JSON.parse(JSON.stringify(this.myInfo))
				dataMy.chatId = Date.now()
				dataMy.content = val
				this.messages.push(dataMy)
				this.sendData.push({role:dataMy.role,content:dataMy.content})
				
				let dataAi = JSON.parse(JSON.stringify(this.AIinfo))
				dataAi.chatId = Date.now()
				this.messages.push(dataAi)
				setTimeout(this.showLast,200)
				
				lastData=this.messages[this.messages.length-1]
				try{
					const res = await cAi.chat(this.sendData)
					console.log(res);
					if(res.reply){
						const choice = res.choices[0]
						if(choice.finishReason=='stop'){
							lastData.status=1
						}else{
							lastData.status=2
							this.concatMsg(choice.message)
						}
						lastData.content = res.reply
						this.showLast()
						
						if(res.summarize){
							this.sendData=[{role:dataAi.role,content:res.summarize}]
						}else{
							this.sendData.push({role:dataAi.role,content:res.reply})
						}
					}
				}catch(e){
					//TODO handle the exception
					lastData.status=-1
					lastData.content = '出错了，请稍后询问...'
					this.showLast()
					this.sendData=[]
				}
				// console.log(JSON.stringify(this.messages));
			},
			showLast(){
				setTimeout(()=>{
					
					// #ifndef H5
					uni.pageScrollTo({
					    scrollTop: this.systemInfo.windowHeight,
					    duration: 0
					  })
					// #endif
					this.scrollIntoView ='list-last-item'
					this.$nextTick(()=>{
						this.scrollIntoView =''
					})
				},100)
			}
		},
		async onLoad() {
			this.systemInfo = uni.getSystemInfoSync()
			// #ifdef APP-PLUS
			if(this.systemInfo.safeAreaInsets.bottom==0){
				this.systemInfo.safeAreaInsets.bottom=16
			}
			// #endif
			
			// #ifdef H5
			this.systemInfo.windowHeight-=uni.upx2px(190)
			
			
			// #endif
			
			// console.log(this.systemInfo);
			// #ifndef H5
			uni.onKeyboardHeightChange(res => {
			  console.log(res.height)
			  this.keyboardHeight = res.height
			})
			// #endif
		},
		onReady() {
			this.$nextTick(this.showLast)
		},
	}
</script>

<style lang="scss">
/* #ifndef APP-NVUE */
page{
	background-color: #ffffff;
}
/* #endif */
.page{

}
.bottom{
	position: fixed;
	bottom: 0;
	width: 100%;
	background-color: #f8f8f8;
}

// .safe-bottom{
// 	padding-bottom: constant(safe-area-inset-bottom)!important;
// 	padding-bottom: env(safe-area-inset-bottom) !important;
// }
.msg-list{
	// height: 100vh;
	
}
.list-last-item{
	height: 80px;
}
</style>
